//
//  MainHomeViewController.m
//  E_Supermarket_Slient
//
//  Created by osoons on 15/6/11.
//  Copyright (c) 2015年 E_Supermarket_Slient. All rights reserved.
//

#import "HomeViewController.h"
#import "SearchListViewController.h"
#import "HomeRootBannerCell.h"
#import "NotLoggedInViewController.h"
#import "ClassSerchViewController.h"
#import "ProdectDetailViewController.h"
#import "KRLCollectionViewGridLayout.h"
#import "FPPopoverController.h"
#import "MainTabbarController.h"
#import "FPPopoverView.h"
#import "FPTouchView.h"
#import "CollectionViewController.h"
#import "BaseUrlConfig.h"
#import "AFNetworking.h"
#import "ShareUserModel.h"
#import "SDImageCache.h"
#import "UIButton+WebCache.h"
#import "UIButton+AFNetworking.h"
#import "MenuCell.h"

#import "BusinessGoodsCell.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "TestCollectionViewController.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "HistoryTabCell.h"
#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"

#import "GetRemandModle.h"
#import "CDPImageCollectionView.h"
@interface HomeViewController ()<CDPImageCollectionViewDelegate>
{
    
    NSDictionary  * dicResponJson;
    NSTimer  *timer_;
    NSInteger currentPage_;
    NSUInteger currentNum;
    NSInteger   pageNum;
    CollectionViewController *controller;
    BOOL isShow;
    BOOL  isRequset;
    NSUInteger pageCount;
    UIButton * button;
}
@property (strong, nonatomic) IBOutlet CDPImageCollectionView * imageCollectionView;

@property (strong, nonatomic) NSString * strKwyWord;
@end

@implementation HomeViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
//    ShareUserModel * userShare = [ShareUserModel shareUserModel];
//    if (!userShare.isLogined)
//        {
//        NotLoggedInViewController *  NotLoggedInView  =[[NotLoggedInViewController alloc] initWithNibName:@"NotLoggedInViewController" bundle:nil];
//        [self presentViewController: NotLoggedInView animated:NO completion:NULL];
//        }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [self stopTimer];

}
-(void)viewDidAppear:(BOOL)animated
{

        if (isRequset)
        {
            isRequset = NO;

            [self getRecommendCommoditysRequest];
            [self getHotCommoditysRequest];
//            [self startTimer];

            //将所需图片url集合成一个数组
//            NSArray *imageArr=[NSArray arrayWithObjects/Users/shaorui/邵瑞/学习记录/PalmChangtuApp/PalmChangtuApp/PalmChangtu/PalmChangtu/Home/HomeViewController.m:
//                               @"http://wenwen.sogou.com/p/20100718/20100718135522-650851011.jpg",
//                               @"http://img2.3lian.com/2014/f2/123/d/62.jpg",
//                               @"http://d.hiphotos.baidu.com/zhidao/pic/item/562c11dfa9ec8a13e028c4c0f603918fa0ecc0e4.jpg",
//                               @"http://img4q.duitang.com/uploads/item/201503/02/20150302165008_HPttF.thumb.700_0.png",
//                               @"http://e.hiphotos.baidu.com/exp/w=500/sign=f03fa87b39292df597c3ac158c305ce2/7e3e6709c93d70cf5f16c759fbdcd100bba12bf1.jpg",
//                               nil];

         
        }

    
    
}
#pragma mark CDP _imageCollectionViewDelegate
-(void)didSelectImageWithNumber:(NSInteger)number{
    
    GetRemandModle * modelTemp =  [_arrayBannerData objectAtIndex:number];

    ProdectDetailViewController * detail  = [[ProdectDetailViewController alloc] initWithNibName:@"ProdectDetailViewController" bundle:nil  ];
    detail.model = modelTemp;
    
    [self presentViewController:detail animated:YES completion:0 ];


}

- (void)viewDidLoad {
    [super viewDidLoad];
    isRequset = YES;

    _tabView.hidden =YES;
    currentNum =  0;
    pageNum = 10;

    isRequset = YES;

    [_v_Top.lalTitel setText:@""];
    [_v_Top.lalTitel setHidden:YES];
    [_v_Top.btnGoback setHidden:YES];
    _v_Top.parentController = self.navigationController;
    
    _textSearch.delegate = self;

    self.searchText.delegate = self;
    self.searchText.backgroundColor = [UIColor clearColor];

    [self.btnLeftSlide removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnLeftSlide addTarget:self action:@selector(btnLeftSlideAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnSearch removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnSearch addTarget:self action:@selector(btnSearch:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    _arrayBannerData = [[NSMutableArray alloc]  init];
  
    _arrayMenuData = [[NSMutableArray alloc]  init];

    
    NSString * path=[[NSBundle mainBundle] pathForResource:@"localType" ofType:@"json"];
    // path=@"app_menu";
    
    NSData * jsonData=[NSData dataWithContentsOfFile:path];
    
    NSString * jsonString=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    dicResponJson =[[MainTabbarController ShareTabBarController] dictionaryWithJsonString:jsonString];
    

    _arrButtionData =[[NSMutableArray alloc] initWithObjects:_btnOne,_btnTwwo,_btnThree,_btnFour,_btnFive,_btnSix,_btnSeven,_btnEhight, nil];
    
    _arrLabData = [[NSMutableArray alloc ]  initWithObjects: _labOne,_labTwo,_labThree,_labFour,_labFive, _labSix,_labSeven,_labEhight,nil];

    
    NSArray *arrBussi = [dicResponJson objectForKey:@"arr"];
    if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
    {

        _arrLocalTypeData = [[NSMutableArray alloc]  init];

        for (NSDictionary *dicTmp in arrBussi)
        {
            
            
            if([[dicTmp objectForKey:@"parentId"] integerValue]==0)
            {
            
                NSError *error = nil;
                localJSONModel *modelTmp =
                [MTLJSONAdapter modelOfClass:[localJSONModel class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrLocalTypeData addObject:modelTmp];
                }
                
            }
   
        }
    
    }
    
    for (int s=0; s<_arrButtionData.count; s++) {
        
        
        localJSONModel * model  = [_arrLocalTypeData objectAtIndex:s];
        
        UIButton * btbTag = [_arrButtionData objectAtIndex:s];
        [btbTag addTarget:self action:@selector(btnButtionAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel * labtext = [_arrLabData objectAtIndex:s];
        labtext.text = model.name;
        btbTag.tag =s+1;
        btbTag.titleLabel.tag = model.parentId.integerValue;
        
        
    }
    

    

    
//    localJSONModel * model0 = [_arrLocalTypeData objectAtIndex:0];
//    
//    self.labOne.text = model0.name;
//    
//    localJSONModel * model1 = [_arrLocalTypeData objectAtIndex:1];
//    
//    self.labTwo.text = model1.name;
//    localJSONModel * model2 = [_arrLocalTypeData objectAtIndex:2];
//    self.labThree.text = model2.name;
//
//    localJSONModel * model3 = [_arrLocalTypeData objectAtIndex:3];
//    self.labFour.text = model3.name;
//
//    localJSONModel * model4 = [_arrLocalTypeData objectAtIndex:4];
//    self.labFive.text = model4.name;
//
//    localJSONModel * model5 = [_arrLocalTypeData objectAtIndex:5];
//    self.labSix.text = model5.name;
//
//    localJSONModel * model6 = [_arrLocalTypeData objectAtIndex:6];
//    self.labSeven.text = model6.name;
//
//    localJSONModel * model7 = [_arrLocalTypeData objectAtIndex:7];
//    
//    self.labEhight.text = model7.name;
//    
    
    
    
    
    _arrRemandData = [[NSMutableArray alloc]  init];
    [self SetBannerCollectionView];
    [self.MenuCollectionView reloadData];
        
    [self setupRefresh];

    // Do any additional setup after loading the view from its nib.
}
-(void)userSearchTextString:(NSString *)str
{

    self.strKwyWord = [NSString stringWithFormat:@"%@",str];
    [self getHomeActionRequest];

}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    SearchListViewController *   SearchListView  = [[SearchListViewController alloc] initWithNibName:@"SearchListViewController" bundle:nil];
    SearchListView.delegateKeyWord = self;

    [self presentViewController:SearchListView animated:YES completion:^{
        
    }];
    
    if (textField == self.searchText) {

        self.tabView.hidden = NO;
        
        
        
        if ([_arrHistoryData count]!=0) {
            
            [button setTitle:@"清空历史记录" forState:UIControlStateNormal];
            
            
        }
        else
            {
            
            [button setTitle:@"无搜索历史记录" forState:UIControlStateNormal];
            
            
            
            }
        
        


    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{



    if (textField.returnKeyType == UIReturnKeySearch)
    {
    
    
    
    self.tabView.hidden = YES;
    
    if(self.searchText.text.length!=0)
        {
        
        [_arrHistoryData addObject:self.searchText.text];
        
        
        }
    
    if([_arrHistoryData count]==0)
        {
        
        self.tabView.hidden = NO;
        self.tabView.tableHeaderView.frame = CGRectMake(0, 0, 0, 0);
        
        
        }
    [self getHomeActionRequest];
    [[self tabView] reloadData];
    
    

    }

    [textField resignFirstResponder];
    return YES;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{


    return YES;

}// return NO to not become first responder
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{


    

//    action.frame  = CGRectMake(0, 0, 0, 0);


 
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
// called when keyboard search button pressed
{


}
-(void)btnSearch:(UIButton *)Search
{
    
    [self.view endEditing:YES];
    self.tabView.hidden = YES;


    if(self.searchText.text.length!=0)
    {

        [_arrHistoryData addObject:self.searchText.text];
    }


    [self getHomeActionRequest];

//    TestCollectionViewController * test  = [[TestCollectionViewController alloc] initWithNibName:@"TestCollectionViewController" bundle:nil];
//    
//
//    
//    TestCollectionViewController * test  = [[TestCollectionViewController alloc] initWithNibName:@"TestCollectionViewController" bundle:nil];
//    
//
//    
//
//    [self.navigationController pushViewController:test animated:YES];

   
}

#pragma mark - schedule tasks

-(void)SlideBanner:(NSTimer *)timer
{
    BOOL animate = YES;
    if([_arrayBannerData count]!=0)
    {
        
        currentPage_++;
        if (currentPage_ >= [_arrayBannerData count]) {
            currentPage_ = 0;
            animate = NO;
        }
        
        NSIndexPath *index = [NSIndexPath indexPathForRow:currentPage_ inSection:0];
        [_RollingScrollView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionNone animated:animate];
        
    }
    
}

- (void)startTimer {
    timer_ = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:3.0] interval:3.0 target:self selector:@selector(SlideBanner:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer_ forMode:NSRunLoopCommonModes];
    
}

- (void)stopTimer
{
    [timer_ invalidate];
    timer_ = nil;
}


#pragma mark - 布局collectionview

-(void)SetBannerCollectionView
{

    //user nib
       CGFloat widthFlow  = self.RollingScrollView.frame.size.width;
    CGFloat heightFlow = self.RollingScrollView.frame.size.height;
    
    UICollectionViewFlowLayout *flowOut = [[UICollectionViewFlowLayout alloc] init];
    [flowOut setItemSize:CGSizeMake(widthFlow, heightFlow)];
    [flowOut setMinimumLineSpacing:0.0];
    [flowOut setMinimumInteritemSpacing:0.0];
    [flowOut setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [self.RollingScrollView setCollectionViewLayout:flowOut];
    
    //user nib
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([ HomeRootBannerCell class]) bundle:nil];
    [self.RollingScrollView registerNib:nib forCellWithReuseIdentifier:[NSString stringWithFormat:@"%@", [HomeRootBannerCell class]]];
    
    //user nib
    [self.RollingScrollView setDelegate:self];
    [self.RollingScrollView setDataSource:self];

    [self.RollingScrollView setPagingEnabled:YES];
    
    
    //    TableView
    //user nib
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([BusinessGoodsCell class]) bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [BusinessGoodsCell class]]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tag = 2000;



    //    TableView
    //user nib
    UINib *nibCellhis = [UINib nibWithNibName:NSStringFromClass([HistoryTabCell class]) bundle:nil];
    [self.tabView registerNib:nibCellhis forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [HistoryTabCell class]]];
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabView.dataSource = self;
    self.tabView.delegate = self;
    self.tabView.tag = 1000;
    self.tabView.hidden = YES;

    _arrHistoryData = [[NSMutableArray alloc] init];

    _arrData = [[NSMutableArray alloc] init];
    



}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (tableView.tag == 1000) {
        
        UIView * viewHeader = [[UIView alloc] init];
#warning         // WARNING: do not set translatesAutoresizingMaskIntoConstraints to NO
        viewHeader.frame = CGRectMake(0, 0, self.tabView.frame.size.width, 40);
        self.tabView.tableHeaderView = viewHeader;
        viewHeader.backgroundColor = [UIColor grayColor];
        
        
//        UIView * viewFooter = [[UIView alloc] init];
//        viewFooter.frame = CGRectMake(0, 0, self.tabView.frame.size.width, 45);
//        self.tabView.tableFooterView = viewFooter;
        
        button = [[UIButton alloc] init];
//        button.backgroundColor =[UIColor greenColor];
        [button setTitle:@"清空历史记录" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.frame = viewHeader.bounds;
        [button removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
        
        [button addTarget:self action:@selector(buttionAction:) forControlEvents:UIControlEventTouchUpInside];
        [viewHeader bringSubviewToFront:button];
        [viewHeader addSubview:button];
        
        return  viewHeader;
        

    }
    else
        
        return nil;
  }
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    if (tableView.tag == 1000) {
        return 40;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1000) {
        return 40;
    }
    return 0;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [[[UIApplication sharedApplication].delegate window]endEditing:YES];
}
-(void)buttionAction:(UIButton *)action
{
    [self.view endEditing:YES];
    _tabView.hidden = YES;
    if ([_arrHistoryData count]!=0) {
        self.tabView.hidden = YES;
        [_arrHistoryData removeAllObjects];
        [self.tabView reloadData];
    }
}


#pragma mark -UICollectionView

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    

        return 1;

    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
        return self.arrayBannerData.count;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    

        //
        static NSString *cellIdent = @"HomeRootBannerCell";

    HomeRootBannerCell *  cell = ( HomeRootBannerCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdent forIndexPath:indexPath];
        
        
        if ([collectionView isEqual:_RollingScrollView])
        {
            
            if ([self.arrayBannerData count] != 0) {


                GetRemandModle *model =[_arrayBannerData objectAtIndex:indexPath.row    ];

                [_RollingPagePoint setCurrentPage:indexPath.row];
                
                _RollingText.text = [NSString stringWithFormat:@"%@",model.name];
                NSURL *urlImage = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,model.photoUrl]];

                [cell.imvMain sd_setImageWithURL:urlImage];

                if (model.photoUrl.length!=0) {
                NSData * data = [NSData dataWithContentsOfURL:urlImage];
                UIImage * imageFit  = [UIImage imageWithData:data];
//                    UIImage * imageFit2 = [self imageCompressForSize:imageFit targetSize:_RollingScrollView.frame.size];
//
//                    UIImage * imageFit3 = [self scaleToSize:imageFit size:_RollingScrollView.frame.size];
//
//                    
//                    UIImage * imageFit4 = [self reSizeImage:imageFit toSize:_RollingScrollView.frame.size];

//                    UIImage * imageFit5 = [self imageNewCompressForWidth:imageFit targetWidth:_RollingScrollView.frame.size.width+25];
//                    UIImage * yasuoImage = [self imageYASUO:imageFit scaledToSize:_RollingScrollView.frame.size];
                    
//                    UIImage * cutImage1 = [self cutImage:imageFit andHeaderView:cell.imvMain];

//                    [cell.imvMain setImage:cutImage1];
                }
      

            }
        }
        return cell;

  

}
#pragma mark - 裁剪图片
- (UIImage *)cutImage:(UIImage*)image andHeaderView:(UIImageView *)bgImgView
{
    //压缩图片
    CGSize newSize;
    CGImageRef imageRef = nil;
    
    if ((image.size.width / image.size.height) < (bgImgView.frame.size.width / bgImgView.frame.size.height)) {
        newSize.width = image.size.width;
        newSize.height = image.size.width * bgImgView.frame.size.height /bgImgView.frame.size.width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
        
    } else {
        newSize.height = image.size.height;
        newSize.width = image.size.height * bgImgView.frame.size.width / bgImgView.frame.size.height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));

    }

    return [UIImage imageWithCGImage:imageRef];
}


#pragma mark - 压缩图片
- (UIImage *)imageYASUO:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
#pragma mark - UICollectionViewDelegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    GetRemandModle * modelTemp  = [_arrayBannerData objectAtIndex:indexPath.row];
    ProdectDetailViewController * detail  = [[ProdectDetailViewController alloc] initWithNibName:@"ProdectDetailViewController" bundle:nil  ];
    detail.model = modelTemp;
    
    [self presentViewController:detail animated:YES completion:0 ];
}



#pragma mark - standard tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (tableView.tag == 1000) {
        return  44;
    }
    else if(tableView.tag == 2000)
    {

        return 100;
    }
    else
    {
        return 0;
    }


}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (tableView.tag == 1000)
    {
        return [_arrHistoryData count];
    }
    else if(tableView.tag == 2000)
    {
    
            return [_arrData count];
    }
else
    return 0;


}


#pragma mark - Standard TableView delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (tableView.tag == 1000)
    {

        static NSString * identifier = @"HistoryTabCell";
        HistoryTabCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        Cell.selectionStyle  = UITableViewCellSelectionStyleNone;

        if ([_arrHistoryData count]!=0) {
            {
            Cell.labHistory.text  = [_arrHistoryData objectAtIndex:indexPath.row];

            }



//                    [Cell.btnDelteHistoryAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
//                    
//                    [Cell.btnDelteHistoryAction addTarget:self action:@selector(btnDelteHistoryAction:) forControlEvents:UIControlEventTouchUpInside];

        }
        
        
        return Cell;

    }
    else if(tableView.tag == 2000)
    {

        static NSString * identifier = @"BusinessGoodsCell";
        BusinessGoodsCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        Cell.selectionStyle  = UITableViewCellSelectionStyleNone;

        if ([_arrData count]!=0) {


            GetRemandModle * dicModel  = [_arrData objectAtIndex:indexPath.row];


            //        NSData * data = [[NSData alloc] initWithBase64EncodedString:[dic objectForKey:@"goods_thumb"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
            //        UIImage *_decodedImage = [UIImage imageWithData:data];

            if (dicModel.photoUrl.length!=0) {

                [Cell.imaegProdect sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,dicModel.photoUrl]] placeholderImage:[UIImage imageNamed:@"SDWebImageDefault"]];
            }
            else{
                [Cell.imaegProdect setImage:[UIImage imageNamed:@"SDWebImageDefault"]];

            }
            Cell.labDescription.text = [NSString stringWithFormat:@"%@",dicModel.content];
            Cell.labTitle.text  = [NSString stringWithFormat:@"%@",dicModel.name];
            Cell.labPrice.text = [NSString stringWithFormat:@"¥%@",dicModel.price];




            //        Cell.btnDelteAction.tag  = indexPath.row;
            //        [Cell.btnDelteAction removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
            //        
            //        [Cell.btnDelteAction addTarget:self action:@selector(btnDelteAction:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
        
        return Cell;
    }
    else
        return nil;


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


    if (tableView.tag ==2000) {
        BusinessGoodsCell * cell =  (BusinessGoodsCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor clearColor];

        GetRemandModle * modelTemp  = [_arrData objectAtIndex:indexPath.row];
        ProdectDetailViewController * detail  = [[ProdectDetailViewController alloc] initWithNibName:@"ProdectDetailViewController" bundle:nil  ];
        detail.model = modelTemp;

        [self presentViewController:detail animated:YES completion:0 ];

    }
    else
    {

        tableView.hidden =YES;

        self.searchText.text =  [_arrHistoryData objectAtIndex:indexPath.row];
        [self getHomeActionRequest];

    }
    

    
    
}
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated
{
    


}


#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    //    if (scrollView == self.CollectionView) {
    //
    //    }
    //    else if(scrollView == self.tableView)
    //    {
    //            onevalues+=10;
    //            twovalues+=onevalues;
    //
    //            [self ShowGoodsRequest:_strMethond andNSinter:nil];
    //
    //    }
    
    
}
#pragma mark - //请求数据

-(void)ShowGoodsRequest:(NSString *)method andNSinter:(NSString *) intValues{
    
    
//    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    //    1食品
    //    2酒水
    //    3烟类
    //    4其他
    
    
    NSString *   strUrl = [NSString stringWithFormat:@"%@",HostServer];
//    NSString *userShopID = [[NSUserDefaults standardUserDefaults]valueForKey:keyUser_id];
    
    NSDictionary *dicJSON   = @{
//                                @"method":method,
//                                @"shop_id":[NSString stringWithFormat:@"%@",userShopID],
//                                @"category":[NSString stringWithFormat:@"%@",intValues],
//                                @"queryStart":[NSNumber numberWithInteger:onevalues],
//                                @"queryNumber":[NSNumber numberWithInteger:pageCount]
                                };
    
    
    //    [NSNumber numberWithInteger:intValues.integerValue]
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJSON options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *param = nil;
    
    param   = @{
                @"data":jsonString,
                };
    
    
    NSLog(@"data  %@",[param objectForKey:@"data"]);
    
    
    [manager GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        
        NSLog(@"%@",responseObject);
        
        NSArray * arr  = responseObject;
        //        NSDictionary * dicRespon  = responseObject;
        [self ShowGoodsListRequestWith:arr];
        
//        [[LoadingView shareLoadingView] dismissAnimated:YES];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
//        [[LoadingView shareLoadingView] dismissAnimated:YES];
//        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }];
    
    
}
-(void)ShowGoodsListRequestWith:(NSArray *)dicRespon
{
    
    
    if (![dicRespon isEqual:[NSNull null]] && [dicRespon isKindOfClass:[NSArray class]])
    {
        
        [_arrData removeAllObjects];
        
        _arrData = [dicRespon mutableCopy];
        
             [self.tableView reloadData];
    
        
    }
}


-(void)btnDelteHistoryAction:(UIButton *)delteHistoryAction

{
    


}


-(void)btnLeftSlideAction:(UIButton *)LeftSlideAction

{
    
    
}








-(void)popover:(id)sender andArr:(NSMutableArray * )arrr;
{
    //the controller we want to present as a popover
    controller = [[CollectionViewController alloc] initWithNibName:@"CollectionViewController" bundle:nil];
    
    controller.delegate = self;
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
    controller.typePop  = popover;
    controller.arrayMenuData = arrr;

    popover.view.backgroundColor = [UIColor clearColor];
    popover.delegate = self;

//
    popover.arrowDirection = FPPopoverArrowDirectionUp;
    popover.tint = FPPopoverLightGrayTint;
    popover.border = NO;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        popover.contentSize = controller.view.frame.size;
    }
    popover.arrowDirection = FPPopoverArrowDirectionVertical;
    

    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
}


- (void)presentedNewPopoverController:(FPPopoverController *)newPopoverController
          shouldDismissVisiblePopover:(FPPopoverController*)visiblePopoverController
{
    [visiblePopoverController dismissPopoverAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



-(void)selectedOneSelectType:(localJSONModel *)localMode
{

    
    
    
    self.strType = [NSString stringWithFormat:@"%@",localMode.name];

    
    [self ShowGoodsRequest:self.strType andNSinter:self.strType];
    

    if ([[ShareUserModel shareUserModel] isLogined])
    {
        ClassSerchViewController *  SerchClassView =[[ClassSerchViewController alloc] initWithNibName:@"ClassSerchViewController" bundle:nil];

        SerchClassView.strType = [NSString stringWithFormat:@"%@",localMode.localTypeID];
        SerchClassView.mdoelType = localMode;

        [self presentViewController: SerchClassView animated:YES completion:^{

        }];

        
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:@"请登录"];

        NotLoggedInViewController *  NotLoggedInView =[[NotLoggedInViewController alloc] initWithNibName:@"NotLoggedInViewController" bundle:nil];

        [self presentViewController: NotLoggedInView animated:YES completion:^{

        }];

    }
    

    
    
    
    
}


-(void)btnButtionAction:(UIButton *)sender

{

    NSLog(@"%d",sender.tag);
    NSLog(@"%d",sender.titleLabel.tag);
    _arrayMenuData = [[NSMutableArray alloc]   init];
    
    NSArray *arrBussi = [dicResponJson objectForKey:@"arr"];
    if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
    {
        
        
        for (NSDictionary *dicTmp in arrBussi)
        {
            
            
            if([[dicTmp objectForKey:@"parentId"] integerValue]==sender.tag)
            {
                
                NSError *error = nil;
                localJSONModel *modelTmp =
                [MTLJSONAdapter modelOfClass:[localJSONModel class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrayMenuData addObject:modelTmp];
                }
                
            }
            
        }
        
    }
    
    

    
    [self popover:sender andArr:_arrayMenuData];

    


}

- (IBAction)btnOneAction:(id)sender {
    
//   _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"烟酒",@"零食",@"奶制品",@"水果",@"蔬菜粮油",@"五金灯具",@"日化洗涤",@"化妆美容",@"文教",@"日用厨具",@"其他", nil];
//    
//    [self popover:sender andArr:_arrayMenuData];
    
}
- (IBAction)btnTwo:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"特色",@"小吃",@"烧烤",@"快餐", nil];
//    [self popover:sender andArr:_arrayMenuData];
}
- (IBAction)btnThree:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"洗涤",@"干洗",@"钟点保洁", nil];
//    [self popover:sender andArr:_arrayMenuData];
}
- (IBAction)btnFour:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"常备药品",@"胃肠皮肤",@"心脑肝胆",@"妇科儿童",@"男科泌尿",@"医疗器械", @"健康保健",@"中西诊所",nil];
//    [self popover:sender andArr:_arrayMenuData];
}
- (IBAction)btnFive:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"小米",@"苹果",@"三星",@"联想",@"华为",@"酷派",@"OPPO",@"VIVO",@"国产其他",@"手机配件", nil];
//    [self popover:sender andArr:_arrayMenuData];

}

- (IBAction)btnSix:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"笔记本",@"电脑配件",@"网络监控",@"电视",@"冰箱",@"空调",@"洗衣机",@"小家电",@"其他", nil];
//    [self popover:sender andArr:_arrayMenuData];

}
- (IBAction)btnSeven:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"近视框架",@"美瞳隐形",@"定制加工",@"眼镜片",@"太阳镜",@"腕表",@"挂钟",@"其他", nil];
//    [self popover:sender andArr:_arrayMenuData];

}
- (IBAction)btnEhight:(id)sender {
//    _arrayMenuData = [[NSMutableArray alloc] initWithObjects:@"男装",@"女装",@"鞋店",@"户外运动",@"孕婴玩具",@"内衣",@"箱包",@"饰品",@"其他", nil];
//    [self popover:sender andArr:_arrayMenuData];

}



#pragma mark 集成刷新控件
- (void)setupRefresh
{
    
        // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.scroll addHeaderWithTarget:self action:@selector(headerRereshing)];
        // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.scroll.headerPullToRefreshText = headerPullToRefreshTextkey;
    self.scroll.headerReleaseToRefreshText  = headerReleaseToRefreshTextkey;
    self.scroll.headerRefreshingText = headerRefreshingTextKey;
    
        // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.scroll addFooterWithTarget:self action:@selector(footerRereshing)];
    self.scroll.footerPullToRefreshText = footerPullToRefreshTextKey;
    self.scroll.footerReleaseToRefreshText =footerPullToRefreshTextKey;
    self.scroll.footerRefreshingText = footerRefreshingTextKey;
    
}

-(void)headerRereshing{
    
    currentNum  = pageNum;
    
    
    pageNum = currentNum + pageNum ;
    NSLog(@"--------%d-----\n--------%d",currentNum,pageNum);
    
    

    [self getHotCommoditysRequest];


    [self.scroll headerEndRefreshing];
    
}

-(void)footerRereshing{
    
    currentNum  = pageNum;
    
    
    pageNum = currentNum + pageNum ;


    NSLog(@"--------%d-----\n--------%d",currentNum,pageNum);
    

    
    [self getHotCommoditysRequest];
    [self.scroll footerEndRefreshing];

    
    
}


#pragma mark - network request all_commodity_TypeRequest

-(void)getRecommendCommoditysRequest
{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
        manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getRecommendCommoditysAction];
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];
    NSDictionary *params =  nil;
    if (!shareUser.isLogined) {
        params = @{
                   
                   @"loginName":@"",
                   @"sessionId":@""
                   };

    }
    else
        {
            params = @{
                       
                             @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]
                             
                             };
        }
    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
         
         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         
         NSDictionary * dicRespon = responseObject;
         [self RequestSuccessWith:dicRespon];
         
         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    
    NSString * code = [dicRespon objectForKey:@"success"];
    
    if (code.integerValue ==1)
    {
        

        [_arrayBannerData removeAllObjects];
        
        NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
        if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
        {
            for (NSDictionary *dicTmp in arrBussi)
            {
                NSError *error = nil;
                GetRemandModle *modelTmp =
                [MTLJSONAdapter modelOfClass:[GetRemandModle class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrayBannerData addObject:modelTmp];
                }
            }

        }
        
        [_RollingPagePoint setNumberOfPages:[_arrayBannerData count]];

        // _imageCollectionView为横向滚动
        self.imageCollectionView =[[CDPImageCollectionView alloc] initWithFrame:self.imageCollectionView.frame andImageUrlArr:self.arrayBannerData scrollDirection:UICollectionViewScrollDirectionHorizontal];

        
//        [ _imageCollectionView openTheTimerAndSetTheDuration:2];
        
        
        //代理方法获得点击第几张图片,如不需要可不设置
        self.imageCollectionView.delegate=self;
        [self.view addSubview: _imageCollectionView];

        [self.RollingScrollView reloadData];
//        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}





#pragma mark - network request getHotCommoditysRequest

-(void)getHotCommoditysRequest
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getHotCommoditysAction];
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];
    NSDictionary *params  = nil;
    if (!shareUser.isLogined) {
        params = @{
                   @"currentNum":[NSNumber numberWithInteger:currentNum],
                   @"pageNum":[NSNumber numberWithInteger:pageNum],
                   @"loginName":@"",
                   @"sessionId":@""
                   };
    }
    else
        {
        
            params = @{
                   
                   @"currentNum":[NSNumber numberWithInteger:currentNum],
                   @"pageNum":[NSNumber numberWithInteger:pageNum],
                   @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                   @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]
                   };

        }




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self GGRequestSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)GGRequestSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    
    if (code.integerValue ==1)
    {



        NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
    

    if (arrBussi.count==0) {
        
        currentNum  = 0 ;
        
        
        pageNum = 10 ;

        
    }
    
    
    
        if (arrBussi && arrBussi.count!=0 && [arrBussi isKindOfClass:[arrBussi class]])
        {
        [_arrData removeAllObjects];

            for (NSDictionary *dicTmp in arrBussi)
            {

                NSError *error = nil;
                GetRemandModle *modelTmp =
                [MTLJSONAdapter modelOfClass:[GetRemandModle class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrData addObject:modelTmp];
                }
            }
        
        [self.tableView reloadData];
        
        [self.scroll footerEndRefreshing];
        

        }



   
//        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}


#pragma mark - network request getHomeActionRequest

-(void)getHomeActionRequest
{
    
    [self.view endEditing:YES];
    
    
    [[[UIApplication sharedApplication].delegate window]endEditing:YES];
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getCommoditys_homeAction];
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

    NSDictionary *params = @{


                                 @"commodityName":self.strKwyWord,
                                 @"currentNum":[NSNumber numberWithInteger:currentNum],
                                 @"pageNum":[NSNumber numberWithInteger:pageNum],
                                 @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                                 @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]

                             };




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self getHomeActionSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)getHomeActionSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {


    
        self.strKwyWord = @"";
        [_arrData removeAllObjects];

        NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
        if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
        {
            for (NSDictionary *dicTmp in arrBussi)
            {
                NSError *error = nil;
                GetRemandModle *modelTmp =
                [MTLJSONAdapter modelOfClass:[GetRemandModle class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrData addObject:modelTmp];
                }
            }

        }



        [self.tableView reloadData];
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

        
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}

    //指定宽度按比例缩放
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height/(width/targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight);
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth);
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}

    //按比例缩放,size 是你要把图显示到 多大区域 CGSizeMake(300, 140)
-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
            
        }
        else{
            
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}

//
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
        // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
        // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        // 使当前的context出堆栈
    UIGraphicsEndImageContext();
        // 返回新的改变大小后的图片 
    return scaledImage; 
}
//2.自定长宽
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
//1.等比率缩放
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize

{
    
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}
//3.处理某个特定View
//只要是继承UIView的object 都可以处理
//必须先import QuzrtzCore.framework
                            
                            
 -(UIImage*)captureView:(UIView *)theView
                            
{
    CGRect rect = theView.frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
    
    }

    //1. 从UIView中获取图像相当于窗口截屏。

//(ios提供全局的全屏截屏函数UIGetScreenView(). 如果需要特定区域的图像，可以crop一下)
//
//CGImageRef screen = UIGetScreenImage();
//UIImage* image = [UIImage imageWithCGImage:screen];

/*
 2. 对于特定UIView的截屏。
 
 （可以把当前View的layer，输出到一个ImageContext中，然后利用这个ImageContext得到UIImage）
 
 -(UIImage*)captureView: (UIView *)theView
 {
 CGRect rect = theView.frame;
 UIGraphicsBeginImageContext(rect.size);
 CGContextRef context =UIGraphicsGetCurrentContext();
 [theView.layer renderInContext:context];
 UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 
 return img;
 }
 */

/*
 3. 如果需要裁剪指定区域。
 
 （可以path & clip，以下例子是建一个200x200的图像上下文，再截取出左上角）
 
 UIGraphicsBeginImageContext(CGMakeSize(200,200));
 CGContextRefcontext=UIGraphicsGetCurrentContext();
 UIGraphicsPushContext(context);
 // ...把图写到context中，省略[indent]CGContextBeginPath();
 CGContextAddRect(CGMakeRect(0,0,100,100));
 CGContextClosePath();[/indent]CGContextDrawPath();
 CGContextFlush(); // 强制执行上面定义的操作
 UIImage* image = UIGraphicGetImageFromCurrentImageContext();
 UIGraphicsPopContext();

 */

/*5.  互相转换UImage和CGImage。
 
 （UImage封装了CGImage, 互相转换很容易）
 
 UIImage* imUI=nil;
 CGImageRef imCG=nil;
 imUI = [UIImage initWithCGImage:imCG];
 imCG = imUI.CGImage;
*/


#pragma mark - 图片显示指定宽度按比例缩放
-(UIImage *) imageNewCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height/(width/targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}

@end
